package com.quanyan.user.service.impl;

import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.AssetsPayReceive;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.request.ReqUserAccumulateModify;
import com.quanyan.assets.response.RespUserAccumulateModify;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.TbUserInviteMapper;
import com.quanyan.user.mapper.TbUserMapper;
import com.quanyan.user.model.db.*;
import com.quanyan.user.request.ReqUserInvite;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInvite;
import com.quanyan.user.service.UserInviteService;
import com.quanyan.user.service.UserQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;

/**
 * Created by jian.zhou on 2016/7/19.
 */
@Service
public class UserInviteServiceImpl implements UserInviteService {

    private static final Logger logger = LoggerFactory.getLogger(UserInviteServiceImpl.class);

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private TbUserInviteMapper tbUserInviteMapper;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private UserAssetsService userAssetsService;

    @Autowired
    private TbUserMapper tbUserMapper;

    @Override
    public RespUserInvite isNewUser(ReqUserInvite reqUserInvite) {
        Integer inviteUid = reqUserInvite.getInviteUid();
        String inviteToMobile = reqUserInvite.getInviteToMobile();
        logger.info("开始邀请用户：{}",reqUserInvite.toString());
        RespUserInvite respUserInvite = new RespUserInvite();
        TbUser tbUser = this.getUser(inviteToMobile);
        TbTask fromTask =(TbTask)myRedisTemplate.hget(UserConstants.UC_SYS_TASK, String.valueOf(TaskEnum.TASK_ENUM_USER_REGISTER_INVITE_FROM.getId()));
        respUserInvite.setEggNum(fromTask.getReward().intValue());

        if(tbUser != null){ //已经注册
            logger.info("该用户已经注册！");
            respUserInvite.setStatus(Constants.RespUserInviteStatus.REGISTER_ED);
            respUserInvite.setDesc("你已经是百灵鸟用户");
            return respUserInvite;

        }else{ //未注册
            logger.info("开始查找用户邀请情况----------》");
            TbUserInviteExample example = new TbUserInviteExample();
            TbUserInviteExample.Criteria criteria = example.createCriteria();
            criteria.andInviteToUserMobileEqualTo(inviteToMobile);
            int count  = tbUserInviteMapper.countByExample(example);
            if(count > 0){
                logger.info("该用户已经被邀请过");
                respUserInvite.setStatus(Constants.RespUserInviteStatus.INVITE_ED);
                respUserInvite.setDesc("你已经被邀请过了");
                return respUserInvite;
            }

            logger.info("开始邀请用户--------------");
            TbUser user = userQueryService.getUser(inviteUid);
            if (user != null) {
                TbUserInvite tbUserInvite = new TbUserInvite();
                tbUserInvite.setInviteUserId(inviteUid);
                tbUserInvite.setInviteUserMobile(user.getMobile());
                tbUserInvite.setInviteToUserMobile(inviteToMobile);
                tbUserInvite.setIsDelete(Constants.IS_DELETE_FALSE);
                tbUserInvite.setCreateTime(new Date());
                tbUserInvite.setUpdateTime(new Date());
                tbUserInvite.setStatus(UserConstants.UserInvite.NO_RECEIVE);
                tbUserInviteMapper.insert(tbUserInvite);
                logger.info("邀请用户结束--------------");
                respUserInvite.setStatus(Constants.RespUserInviteStatus.INVITE);
                respUserInvite.setDesc(respUserInvite.getEggNum() + "鸟蛋已存入手机号" + inviteToMobile);
            } else {
                respUserInvite.setStatus(Constants.RespUserInviteStatus.INVITE_NOT_EXIST);
                respUserInvite.setDesc("邀请您的用户不存在");
            }
            return respUserInvite;
        }

    }


    /**
     * 被邀请新用户注册奖励
     * @param
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void rewardUserRegister(Integer uid){
        logger.info("开始给邀请用户奖励------》{}",uid);
        TbUser user = userQueryService.getUser(uid);//被邀请人
        if (user == null)
            return;
        TbUserInviteExample example = new TbUserInviteExample();
        TbUserInviteExample.Criteria criteria = example.createCriteria();
        criteria.andInviteToUserMobileEqualTo(user.getMobile());
        List<TbUserInvite> tbUserInviteList = tbUserInviteMapper.selectByExample(example);
        if(tbUserInviteList != null && tbUserInviteList.size() > 0){ // 是邀请的用户
            TbUserInvite tbUserInvite = tbUserInviteList.get(0);
            TbTask fromTask =(TbTask)myRedisTemplate.hget(UserConstants.UC_SYS_TASK, String.valueOf(TaskEnum.TASK_ENUM_USER_REGISTER_INVITE_FROM.getId()));
            TbTask toTask =(TbTask) myRedisTemplate.hget(UserConstants.UC_SYS_TASK, String.valueOf(TaskEnum.TASK_ENUM_USER_REGISTER_INVITE_TO.getId()));

            tbUserInvite.setInviteReward(fromTask.getReward().intValue());
            tbUserInvite.setInviteToReward(toTask.getReward().intValue());
            tbUserInvite.setStatus(UserConstants.UserInvite.YES_RECEIVE);
            tbUserInviteMapper.updateByPrimaryKeySelective(tbUserInvite);

            APIResponse<RespUserInfoBase> response = userQueryService.queryUserInfo(tbUserInvite.getInviteToUserMobile());

            APIResponse r1 = this.addEggShell(tbUserInvite.getInviteUserId(), TaskEnum.TASK_ENUM_USER_REGISTER_INVITE_FROM.getCode(), tbUserInvite.getId());
            if(!r1.isRet())
                throw new BizException(r1.getErrmsg());

            APIResponse r2 = this.addEggShell(response.getData().getUid(),TaskEnum.TASK_ENUM_USER_REGISTER_INVITE_TO.getCode(),tbUserInvite.getId());
            if(!r2.isRet())
                throw new BizException(r2.getErrmsg());
            logger.info("结束被邀邀请用户增加鸟蛋");
        }

    }

    /**
     * 邀请用户只送邀请人鸟蛋
     * @param reqUserInvite
     * @return
     */
    @Override
    public RespUserInvite inviteUserSendEggs(ReqUserInvite reqUserInvite) {
        Integer inviteUid = reqUserInvite.getInviteUid();
        String inviteToMobile = reqUserInvite.getInviteToMobile();
        logger.info("邀请用户送10个鸟蛋：{}",reqUserInvite.toString());
        RespUserInvite respUserInvite = new RespUserInvite();
        TbUser tbUser = this.getUser(inviteToMobile);

        if(tbUser == null){ //未注册
            logger.info("该用户已经注册！");
            respUserInvite.setStatus(Constants.RespUserInviteStatus.REGISTER_ED);
            respUserInvite.setDesc("你已经是百灵鸟用户");
            return respUserInvite;

        }else{ //已注册
            TbUser user = userQueryService.getUser(inviteUid);
            if (user != null) {
                APIResponse r1 = this.addEggShell(inviteUid, TaskEnum.TASK_ENUM_USER_REGISTER_INVITE_FROM.getCode(), 0);
                if (r1.isRet()) {
                    respUserInvite.setStatus(Constants.RespUserInviteStatus.INVITE);
                } else {
                    respUserInvite.setStatus(Constants.RespUserInviteStatus.REGISTER_ED);
                }
            } else {
                respUserInvite.setStatus(Constants.RespUserInviteStatus.INVITE_NOT_EXIST);
                respUserInvite.setDesc("邀请您的用户不存在");
            }
            return respUserInvite;
        }
    }

    /**
     * 增加蛋壳
     */
    public APIResponse<RespUserAccumulateModify> addEggShell(Integer uid,String businessCode,Integer businessId){
        logger.info("开始增加鸟蛋。。。。。。。。。。");
        APIRequest<ReqUserAccumulateModify> apiRequest = new APIRequest<ReqUserAccumulateModify>();
        ReqUserAccumulateModify r = new ReqUserAccumulateModify();
        r.setUid(uid);
        r.setSystemCode(Constants.USER_CENTER_SYSTEM_CODE);
        r.setBusinessCode(businessCode);
        r.setBusinessId(businessId);
        r.setAssetsType(AssetsType.ASSETS_EGGS.getId().byteValue());
        TbUser tbUser = userQueryService.getUser(uid);
        if(tbUser.getNickName() != null)
            r.setReceiver(tbUser.getNickName());
        else
            r.setReceiver(tbUser.getMobile());
        r.setInfo("成功通过邀请好友注册");
        r.setPayReceive(AssetsPayReceive.SYSTEM.getName());
        apiRequest.setData(r);
        APIResponse<RespUserAccumulateModify> response = userAssetsService.modifyAccumulate(apiRequest);
        return response;
    }

    /**
     * 从数据库中获取用户
      * @param mobile
     * @return
     */
    public TbUser getUser(String mobile){
        TbUserExample example = new TbUserExample();
        TbUserExample.Criteria criteriaMobile = example.createCriteria();
        criteriaMobile.andMobileEqualTo(mobile);
        List<TbUser> tbUserList =  tbUserMapper.selectByExample(example);
        if(tbUserList != null && tbUserList.size() > 0)
            return tbUserList.get(0);
        return null;
    }

}
